package com.ccnu.sm.file;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value="/file")
public class RFileController {
	private static final Log logger = LogFactory.getLog(RFileController.class);
	@RequestMapping(value="/")
	public void root(HttpServletResponse response) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		Map<String, String> actionMap = new HashMap<>();
		actionMap.put("/upload", "进行文件上传");
		actionMap.put("/download", "进行文件下载");
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().println(mapper.writeValueAsString(actionMap));
	}
	
	@RequestMapping(value="/upload", method=RequestMethod.POST)
	public String upload(HttpServletRequest request,
			@RequestParam("description") String description,
			@RequestParam("file") MultipartFile file,
			Model model) throws Exception, Exception {
		logger.info("FileController.upload 正在被调用");		
		if(file.isEmpty()) {
			return "error";
		}

//		String path = request.getServletContext().getRealPath("/images/");
		String path = request.getContextPath();
		String filename = file.getOriginalFilename();
		File filepath = new File(path, filename);

		if(!filepath.getParentFile().exists()) {
			filepath.getParentFile().mkdirs();
		}

		file.transferTo(new File(path + File.separator + filename));

		model.addAttribute("filepath", path + File.separator + filename);
		model.addAttribute("filename", filename);
		return "fileDownload";
	}
	
	@RequestMapping(value="/download")
	public ResponseEntity<byte[]> download(HttpServletRequest request,
			@RequestParam("filename") String filename) throws IOException{
		String path = request.getContextPath();
		
		File file = new File(path + File.separator + filename);
		
		HttpHeaders headers = new HttpHeaders();
		
		String downloadFileName = new String(filename.getBytes());
		
		headers.setContentDispositionFormData("attachment", downloadFileName); // 通知浏览器以attachment方式下载
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);	// 设置为二进制流
		
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);		
	}
}
